import { Card, Breadcrumb, Form, Button, Radio, Input, Upload, Space, Select } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import './index.scss';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import useStore from '@/store';
import { baseURL, http } from '@/utils';
import { useState, useRef, useEffect } from 'react';

const { Option } = Select;

const Publish = () => {
  const [params] = useSearchParams();
  const articleId = params.get('id');
  const form = useRef();
  const navigate = useNavigate();

  const onFinish = async values => {
    const { channel_id, content, title, type } = values;
    const params = {
      channel_id,
      content,
      title,
      type,
      cover: {
        type: type,
        images: fileList.map(item => item.url),
      },
    };
    // 发布/编辑文章
    if (articleId) {
      // 编辑
      await http.put(`/mp/articles/${articleId}?draft=false`, params);
    } else {
      // 新增
      await http.post('/mp/articles?draft=false', params);
    }
    navigate('/article')
  };

  const [imgCount, setImgCount] = useState(1);

  const [fileList, setFileList] = useState([]);
  const fileListRef = useRef([]);
  // 上传成功回调
  const onUploadChange = info => {
    const fileList = info.fileList.map(file => {
      if (file.response) {
        return {
          url: file.response.data.url,
        };
      }
      return file;
    });
    setFileList(fileList);
    fileListRef.current = fileList;
  };

  const radioChange = e => {
    setImgCount(e.target.value);
    if (e.target.value === 1) {
      const img = fileListRef.current.length > 0 ? [fileListRef.current[0]] : [];
      setFileList(img);
    } else if (e.target.value === 3) {
      setFileList(fileListRef.current);
    }
  };

  // 表单回填
  useEffect(() => {
    async function getArticle() {
      const res = await http.get(`/mp/articles/${articleId}`);
      const { cover, ...formValue } = res.data;
      // 动态设置表单数据
      form.current.setFieldsValue({ ...formValue, type: cover.type });
      // 格式化封面图片数据
      const imageList = cover.images.map(url => ({ url }));
      setFileList(imageList);
      setImgCount(cover.type);
      fileListRef.current = imageList;
    }
    articleId && getArticle();
  }, [articleId]);

  const { channelStore } = useStore();

  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{articleId ? '编辑文章' : '发布文章'}</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1, content: 'this is content' }}
          onFinish={onFinish}
          ref={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {channelStore.channelList.map(item => {
                return (
                  <Option value={item.id} key={item.id}>
                    {item.name}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={radioChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {imgCount > 0 && (
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                fileList={fileList}
                onChange={onUploadChange}
                showUploadList
                action={baseURL + `/upload`}
                multiple={imgCount > 1}
                maxCount={imgCount}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill theme="snow" />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {articleId ? '编辑文章' : '发布文章'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Publish;
